<template>
    <div class="clearfix">
        <a-upload-dragger
            name="file"
            :action="$staticUrl"
            @preview="handlePreview"
            :data="uploadData"
            :before-upload="beforeUpload"
            :remove="handleRemove"
            :default-file-list="defaultFileList"
            @change="handleChange"
            :key="key"
        >
            <p class="ant-upload-drag-icon">
                <a-icon :type="iconType" />
            </p>
            <p class="ant-upload-text">
                将文件拖到此处，或<span style='color: #1ab8f3'>点击上传</span>
            </p>
            <p class="ant-upload-hint" v-if='tipText'>
                {{ tipText }}
            </p>
        </a-upload-dragger>
        <a-modal
            class="imgModel"
            :visible="previewVisible"
            :footer="null"
            @cancel="handleCancel"
        >
            <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
    </div>
</template>

<script>
import { getUUID } from '@/plugins/tools'

function getBase64 (file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = error => reject(error)
    })
}
export default {
    name: 'ImageUpload',
    model: {
        prop: 'value',
        event: 'change'
    },
    props: {
        value: {
            type: Array,
            default: () => {
                return []
            }
        },
        isShow: {
            type: Boolean,
            default: () => {
                return true
            }
        },
        typeList: {
            type: Array,
            default: () => {
                return []
            }
        },
        iconType: {
            type: String,
            default: () => {
                return 'cloud-upload'
            }
        },
        tipText: {
            type: String,
            default: () => {
                return ''
            }
        },
        path: {
            type: String,
            default: () => {
                return ''
            }
        },
        // 最多上传数量
        max: {
            type: Number,
            default: () => {
                return 1
            }
        },
        // 文件大小
        fileSize: {
            type: Number,
            default: () => {
                return 10
            }
        },
        customBeforeUpload: {
            type: Function,
            default: () => {
                return Promise.resolve(true)
            }
        }
    },
    data () {
        return {
            previewVisible: false,
            previewImage: '',
            sourceList: [],
            defaultFileList: [],
            uploadData: {
                signature: '',
                'x-cos-security-token': '',
                'Content-Type': '',
                key: '',
                dir: '',
                host: ''
            },
            key: 0
        }
    },
    watch: {
        value: {
            deep: true,
            immediate: true,
            handler (val) {
                if (val === null || val === [] || val === undefined) {
                    return []
                }
                this.sourceList = []
                this.defaultFileList = []
                let count = -1
                const tempList = []
                val.forEach((item) => {
                    let name = ''
                    if (item.includes('?name=')) {
                        name = item.split('?name=')[1]
                    } else {
                        name = item
                    }
                    tempList.push({
                        uid: count,
                        name,
                        status: 'done',
                        url: item
                    })
                    count--
                })
                this.defaultFileList = tempList
                this.$nextTick(() => {
                    this.sourceList = this.defaultFileList.map((item) => {
                        return {
                            _id: item.uid,
                            url: item.url,
                            name: item.name
                        }
                    })
                    this.key++
                })
            }
        }
    },
    methods: {
        handleCancel () {
            this.previewVisible = false
        },
        async handlePreview (file) {
            if (file.name.includes('.pdf')) {
                const url = file.url.replace(/\?/g, '%3F').replace(/=/g, '%3D')
                window.open(this.$staticUrl + url, '_blank')
            } else {
                if (!file.url && !file.preview) {
                    file.preview = await getBase64(file.originFileObj)
                }
                this.previewImage = file.url || file.preview
                this.previewVisible = true
            }
        },
        handleChange ({ file }) {
            if (file.status === 'uploading') {
                return
            }
            if (file.status === 'done') {
                this.sourceList.push({
                    _id: file.uid,
                    url: this.uploadData.key,
                    name: file.name.replace(/,/g, '')
                })
                const temp = []
                this.sourceList.forEach((item) => {
                    temp.push(item.url)
                })
                this.$emit('change', temp)
            }
        },
        beforeUpload (file) {
            return new Promise((resolve) => {
                const uploadPolicy = () => {
                    if (!this.typeList.includes(file.type)) {
                        this.$message.error('上传文件格式不对!')
                        return false
                    }
                    const isLt4M = file.size / 1024 / 1024 < this.fileSize
                    if (!isLt4M) {
                        this.$message.error(`图片大小不能超过${this.fileSize}M!`)
                        return false
                    }
                    const _path = '/' + this.path + '/' + this.$service.dateFormatter('yyyy-MM-dd') + '/'
                    this.$service.getAuthor({ Method: 'POST', Pathname: '/' })
                        .then((info) => {
                            this.uploadData.signature = info.Authorization
                            this.uploadData['x-cos-security-token'] = info.XCosSecurityToken
                            this.uploadData['Content-Type'] = ''
                            this.uploadData.key = _path + getUUID() + '.' + file.name.replace(/,/g, '').split('.').pop() + '?name=' + file.name.replace(/,/g, '')
                            this.uploadData.dir = _path
                            this.uploadData.host = this.$staticUrl
                            resolve(true)
                        })
                }

                this.customBeforeUpload(file).then((r) => {
                    if (r) {
                        uploadPolicy()
                    }
                })
            })
        },
        handleRemove (file) {
            const index = this.sourceList.findIndex(item => item._id === file.uid)
            const num = this.defaultFileList.findIndex(
                item => item.uid === file.uid
            )
            this.defaultFileList.splice(num, 1)
            if (index > -1) {
                const temp = []
                this.sourceList.splice(index, 1)
                this.sourceList.forEach((item) => {
                    temp.push(item.url)
                })
                this.$emit('change', temp)
            }
        }
    }
}
</script>
